import axios from 'axios'
import { Notification , Message,ElLoading} from 'element-ui' //引入element-ui库
import { getToken } from '@/utils/auth'; // 引入Cookies

const contentTypeForm = 'application/x-www-form-urlencoded;charset=UTF-8'
const contentTypeJson = 'application/json'
//arraybuffer	ArrayBuffer对象
//blob	Blob对象
const responseTypeJson = "json"

let loading = null;
axios.defaults.withCredentials =true
// 创建axios实例
const service = axios.create({
  baseURL: process.env.API_ROOT, // 设置请求的基本URL
  timeout: 30 * 1000, // 请求超时时间
   withCredentials: true, //表示跨域请求时是否需要使用凭证
})
// request拦截器

service.interceptors.request.use(
    responseType=>{return responseType},
  config => {
    console.log(config);
    if (config.showLoading) {
        const { url, params, dataType, showLoading = true, responseType = responseTypeJson } = config;
    let contentType = contentTypeForm;
    let formData = new FormData();// 创建form对象
    for (let key in params) {
        formData.append(key, params[key] == undefined ? "" : params[key]);
    }
    if (dataType != null && dataType == 'json') {
        contentType = contentTypeJson;
    }
    // let headers = {
    // }
    config.headers['Content-Type']= contentType,
    config.headers['X-Requested-With']= 'XMLHttpRequest'
    //     if (getToken()) {
    //         config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    //    } else {
    //      config.headers['Authorization'] = `Bearer ${''}`; 
    //    }
        loading = ElLoading.service({
            lock: true,
            text: '加载中......',
            background: 'rgba(0, 0, 0, 0.7)',
        });
    }
      
      return config
  },
  error => {
    if (config.showLoading && loading) {
        loading.close();
    }
    Message.error("请求发送失败");
    return Promise.reject("请求发送失败");
    //   Promise.reject(error)
  }
)
//请求后拦截器
service.interceptors.response.use(
    (response) => {
        const { showLoading, errorCallback, showError = true, responseType } = response.config;
        if (showLoading && loading) {
            loading.close()
        }
        const responseData = response.data;
        if (responseType == "arraybuffer" || responseType == "blob") {
            return responseData;
        }
        //正常请求
        if (responseData.code == 200) {
            return responseData;
        } else if (responseData.code == 201) {
            return responseData;
        } else if (responseData.code == 901) {
            //登录超时
            router.push("/login?redirectUrl=" + encodeURI(router.currentRoute.value.path));
            return Promise.reject({ showError: false, msg: "登录超时" });
        } else {
            //其他错误
            if (errorCallback) {
                errorCallback(responseData.info);
            }
            return Promise.reject({ showError: showError, msg: responseData.info });
        }
    },
    (error) => {
        if (error.config.showLoading && loading) {
            loading.close();
        }
        return Promise.reject({ showError: true, msg: "网络异常" })
    }
);
// 拦截器方式 二
 
// service.interceptors.response.use(
//   res => {
//     if (res.status === 200) {
//       return res.data;
//     } else {
//       return Promise.reject(new Error(res.data.Data.Message || 'Error'));
//     }
//   },
//   error => {
//     Message.error(showStatus(error.response.status)); // , error.response.data
//     return Promise.reject(error);
//   }
// );
 
 
// const showStatus = (code, errMessage) => {
//   let message = '';
//   switch (code) {
//     case 400: message = errMessage || '请求错误(400)'; break;
//     case 401: message = '未授权，请重新登录(401)'; break;
//     case 403: message = '拒绝访问(403)'; break;
//     case 404: message = '请求出错(404),未找到文件'; break;
//     case 408: message = '请求超时(408)'; break;
//     case 500: message = '服务器错误(500)'; break;
//     case 501: message = '服务未实现(501)'; break;
//     case 502: message = '网络错误(502)'; break;
//     case 503: message = '服务不可用(503)'; break;
//     case 504: message = '网络超时(504)'; break;
//     case 505: message = 'HTTP版本不受支持(505)'; break;
//     default: message = `连接出错(${code})!`;
//   }
//   return `${message}`;
// };
const request = (config) => {
    const { url, params, dataType, showLoading = true, responseType = responseTypeJson } = config;
    let contentType = contentTypeForm;
    let formData = new FormData();// 创建form对象
    for (let key in params) {
        formData.append(key, params[key] == undefined ? "" : params[key]);
    }
    if (dataType != null && dataType == 'json') {
        contentType = contentTypeJson;
    }
    let headers = {
        'Content-Type': contentType,
        'X-Requested-With': 'XMLHttpRequest',
    }

    return service.post(url, formData, {
        onUploadProgress: (event) => {
            if (config.uploadProgressCallback) {
                config.uploadProgressCallback(event);
            }
        },
        responseType: responseType,
        headers: headers,
        showLoading: showLoading,
        errorCallback: config.errorCallback,
        showError: config.showError
    }).catch(error => {
        console.log(error);
        if (error.showError) {
            Message.error(error.msg);
        }
        return null;
    });
};
//将service导出
export default service; 